package io.renren.modules.workjobs.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.*;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.CommonBusinessStatus;
import io.renren.modules.common.dao.PositionCertificateDao;
import io.renren.modules.common.dao.PositionWelfareDao;
import io.renren.modules.common.entity.PositionCertificateEntity;
import io.renren.modules.common.entity.PositionWelfareEntity;
import io.renren.modules.common.service.PositionCertificateService;
import io.renren.modules.common.service.PositionWelfareService;
import io.renren.modules.common.viewdo.TreeOption;
import io.renren.modules.companys.dao.CompanyDao;
import io.renren.modules.companys.entity.CompanyEntity;
import io.renren.modules.companys.service.CompanyService;
import io.renren.modules.pdf.entity.ResumeEntityDTO;
import io.renren.modules.resumes.dao.ResumeDao;
import io.renren.modules.resumes.entity.ResumeEntity;
import io.renren.modules.workjobs.dao.DeliveryCreateUserPositionDao;
import io.renren.modules.workjobs.dao.UserPositionDeliverPersonalDao;
import io.renren.modules.workjobs.dao.WorkJobDao;
import io.renren.modules.workjobs.entity.DeliveryCreateUserPositionEntity;
import io.renren.modules.workjobs.entity.UserPositionDeliverPersonalEntity;
import io.renren.modules.workjobs.entity.UserPositionEntity;
import io.renren.modules.workjobs.entity.dto.QueryCondition;
import io.renren.modules.workjobs.entity.dto.SelectCompanyOption;
import io.renren.modules.workjobs.entity.dto.WorkJobEntityDTO;
import io.renren.modules.workjobs.service.DeliveryCreateUserPositionService;
import io.renren.modules.workjobs.service.UserPositionDeliverPersonalService;
import io.renren.modules.workjobs.service.UserPositionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.workjobs.entity.WorkJobEntity;
import io.renren.modules.workjobs.service.WorkJobService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author nyc
 * @email 2691778746@qq.com
 * @date 2022-03-07 17:53:27
 */
@RestController
@RequestMapping("workjobs/workjob")
public class WorkJobController {
    @Autowired
    private ResumeDao resumeDao;
    @Autowired
    private WorkJobService workJobService;
    @Autowired
    private WorkJobDao workJobDao;
    @Autowired
    private PositionWelfareService positionWelfareService;
    @Autowired
    private PositionCertificateService positionCertificateService;
    @Autowired
    private UserPositionService userPositionService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private PositionWelfareDao positionWelfareDao;
    @Autowired
    private PositionCertificateDao positionCertificateDao;
    @Autowired
    private UserPositionDeliverPersonalDao userPositionDeliverPersonalDao;
    @Autowired
    private UserPositionDeliverPersonalService userPositionDeliverPersonalService;
    @Autowired
    private DeliveryCreateUserPositionDao deliveryCreateUserPositionDao;
    @Autowired
    private DeliveryCreateUserPositionService deliveryCreateUserPositionService;
    @Autowired
    private CompanyDao companyDao;

    @GetMapping("/tree-option-ccj")
    public R treeOPtionCCJ(){
        List<TreeOption> listData = workJobService.treeOptionCCJ();
        return R.ok().put("data",listData);
    }

    @GetMapping("/tree-option-ccj/{userId}")
    public R TreeOption(@PathVariable("userId")String userId){
        QueryWrapper<CompanyEntity> wapper = new QueryWrapper<>();
        wapper.eq("create_user_id",userId);
        CompanyEntity company = companyService.getOne(wapper);
        List<String> listData = new ArrayList<>();
        listData.add(company.getTradeId().toString());
        listData.add(company.getClassifyId().toString());
        //listData.add(company.getJobTypeId().toString());
        return R.ok().put("data",listData);
    }

    @PostMapping("/pauseRecruit/{workId}")
    public R pauseRecruit(@PathVariable("workId")String workId){
        WorkJobEntity workJobEntity = workJobDao.selectById(workId);

        if (CommonBusinessStatus.POSITION_STOP.equals(workJobEntity.getJobRecruitStatus())){
            throw new RRException("此职位已经是停止招聘状态。");
        }

        workJobEntity.setJobRecruitStatus(CommonBusinessStatus.POSITION_SUSPEND);
        int isUpdate = workJobDao.updateById(workJobEntity);
        if (isUpdate>0){
            return R.ok().put("msg","状态修改成功");
        }
        return R.error().put("msg","状态修改失败");
    }
    @PostMapping("/stopRecruit/{workId}")
    public R stopRecruit(@PathVariable("workId")String workId){
        WorkJobEntity workJobEntity = workJobDao.selectById(workId);
        workJobEntity.setJobRecruitStatus(CommonBusinessStatus.POSITION_STOP);
        int isUpdate = workJobDao.updateById(workJobEntity);
        if (isUpdate>0){
            return R.ok().put("msg","状态修改成功");
        }
        return R.error().put("msg","状态修改失败");
    }


    @PostMapping("/continueRecruit/{workId}")
    public R continueRecruit(@PathVariable("workId")String workId){
        WorkJobEntity workJobEntity = workJobDao.selectById(workId);

        Integer jobRecruitStatus = workJobEntity.getJobRecruitStatus();
        if (jobRecruitStatus.equals(CommonBusinessStatus.POSITION_STOP)){
            return R.error("此岗位已经停止招聘，不可以在继续招聘了哦");
        }

        workJobEntity.setJobRecruitStatus(CommonBusinessStatus.POSITION_RECRUIT_ING);
        int isUpdate = workJobDao.updateById(workJobEntity);
        if (isUpdate>0){
            return R.ok().put("msg","状态修改成功");
        }
        return R.error().put("msg","状态修改失败");
    }




    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("workjobs:workjob:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = workJobService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("workjobs:workjob:info")
    public R info(@PathVariable("id") String id){
		WorkJobEntity workJob = workJobService.getById(id);

        return R.ok().put("workJob", workJob);
    }

    /**
     * 创建职位的方法，提供给客户端
     */
    @RequestMapping("/save")
    @Transactional
    @RequiresPermissions("workjobs:workjob:save")
    public R save(@RequestBody WorkJobEntityDTO workJobEntityDTO){

        //判断当前用户创建的企业信息是否通过审核，没有通过不允许发布工作职位信息，通过可以发布职位信息
        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("create_user_id",workJobEntityDTO.getCreateUserId());
        CompanyEntity companyEntityInfo = companyService.getOne(wrapper);

        if (companyEntityInfo == null){
            throw new RRException("当前您还没有创建任何的企业信息，请先创建企业信息");
        }

        Integer isPass = companyEntityInfo.getIsPass();
        Integer companyApproveStatus = companyEntityInfo.getCompanyApproveStatus();
        if (isPass == 0 && companyApproveStatus != CommonBusinessStatus.COMPANY_HAVE_APPROVE){
            throw new RRException("企业资质审核没有通过，您还不能发布职位信息");
        }

        WorkJobEntity workJob = new WorkJobEntity();
        BeanUtils.copyProperties(workJobEntityDTO,workJob);
		workJobService.save(workJob);
        ArrayList<String> positionWalfare = workJobEntityDTO.getPositionWalfare();
        ArrayList<String> positionCertifiCate = workJobEntityDTO.getPositionCertifiCate();
        List<PositionWelfareEntity> positionWalfareList = positionWalfare.stream().map(item -> new PositionWelfareEntity(Integer.parseInt(item), workJob.getId())).collect(Collectors.toList());
        List<PositionCertificateEntity> positionCertificateList = positionCertifiCate.stream().map(item -> new PositionCertificateEntity(Integer.parseInt(item), workJob.getId())).collect(Collectors.toList());
        positionWelfareService.saveBatch(positionWalfareList);
        positionCertificateService.saveBatch(positionCertificateList);
        //用户所创建的对应的职位
        userPositionService.save(new UserPositionEntity(workJobEntityDTO.getCreateUserId(),workJob.getId()));
        return R.ok();
    }


    /**
     * 创建职位的方法，提供给服务端
     */
    @RequestMapping("/serverSave")
    @Transactional
    public R serverSave(@RequestBody WorkJobEntityDTO workJobEntityDTO){
        String companyId = workJobEntityDTO.getCompanyId();

        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",companyId);
        CompanyEntity companyEntity = companyDao.selectOne(wrapper);

        if (companyEntity.getIsPass() == 0
                &&
            companyEntity.getCompanyApproveStatus() != CommonBusinessStatus.COMPANY_HAVE_APPROVE){
            throw new RRException("企业资质审核没有通过，您还不能发布职位信息");
        }

        WorkJobEntity workJob = new WorkJobEntity();
        BeanUtils.copyProperties(workJobEntityDTO,workJob);
        workJobService.save(workJob);
        ArrayList<String> positionWalfare = workJobEntityDTO.getPositionWalfare();
        ArrayList<String> positionCertifiCate = workJobEntityDTO.getPositionCertifiCate();
        List<PositionWelfareEntity> positionWalfareList = positionWalfare.stream().map(item -> new PositionWelfareEntity(Integer.parseInt(item), workJob.getId())).collect(Collectors.toList());
        List<PositionCertificateEntity> positionCertificateList = positionCertifiCate.stream().map(item -> new PositionCertificateEntity(Integer.parseInt(item), workJob.getId())).collect(Collectors.toList());
        positionWelfareService.saveBatch(positionWalfareList);
        positionCertificateService.saveBatch(positionCertificateList);
        //用户所创建的对应的职位
        userPositionService.save(new UserPositionEntity(workJobEntityDTO.getCreateUserId(),workJob.getId()));
        return R.ok();
    }

    /**
     * 加载管理员创建的企业信息
     */
    @GetMapping("/company-option/{userId}")
    public R selectCompany(@PathVariable("userId")String userId){

        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("create_user_id",userId);
        List<CompanyEntity> companyEntities = companyDao.selectList(wrapper);
        List<SelectCompanyOption> resList = new ArrayList<>();
        for (CompanyEntity companyEntity:companyEntities){
            SelectCompanyOption selectCompanyOption = new SelectCompanyOption();
            selectCompanyOption.setLabel(companyEntity.getCompanyName());
            selectCompanyOption.setValue(companyEntity.getId());
            resList.add(selectCompanyOption);
        }
        return R.ok().put("data",resList);
    }

    /**
     * 修改
     * TODO
     */
    @RequestMapping("/update")
    @Transactional
    @RequiresPermissions("workjobs:workjob:update")
    public R update(@RequestBody WorkJobEntity workJob){
		workJobService.updateById(workJob);

        return R.ok();
    }

    /**
     * 删除
     */
    @Transactional
    @RequestMapping("/delete")
    @RequiresPermissions("workjobs:workjob:delete")
    public R delete(@RequestBody String[] ids){

        QueryWrapper<PositionWelfareEntity> wrapper = new QueryWrapper<>();
        wrapper.in("position_id",ids);
        List<PositionWelfareEntity> positionWelfareEntities = positionWelfareDao.selectList(wrapper);
        List<Integer> welfareIds = positionWelfareEntities.stream().map(item -> item.getId()).collect(Collectors.toList());
        positionWelfareService.removeByIds(welfareIds);


        QueryWrapper<PositionCertificateEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.in("position_id",ids);
        List<PositionCertificateEntity> positionCertificateEntityList = positionCertificateDao.selectList(wrapper1);
        List<Integer> certificateIds = positionCertificateEntityList.stream().map(item -> item.getId()).collect(Collectors.toList());
        positionCertificateService.removeByIds(certificateIds);


        workJobService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 根据Id显示职位的详情信息
     */
    @GetMapping("/jobInfo/{workId}")
    public R jobInfo(@PathVariable("workId")String workId){

        WorkJobEntity workJobEntity = workJobService.getById(workId);


        if (CommonBusinessStatus.POSITION_NOT_HAVE_APPROVE.equals(workJobEntity.getJobApproveStatus())
            &&
                !(
                   CommonBusinessStatus.POSITION_PUBLISH_NOT_HAVE.equals(workJobEntity.getJobIssueStatus())
                    ||
                   CommonBusinessStatus.POSITION_PUBLISH_HAVEING.equals(workJobEntity.getJobIssueStatus())
                  )
            ){
            workJobEntity.setJobApproveStatus(CommonBusinessStatus.POSITION_HAVEING_APPROVE);
            workJobDao.updateById(workJobEntity);
        }
        return R.ok().put("data",workJobEntity);
    }

    /**
     * 根据职位的Id显示出来行业地址
     */
    @GetMapping("/address-option/{workId}")
    public R jobIndustoryAddressOptionArr(@PathVariable("workId")String workId){
        ArrayList<String> listData = new ArrayList<>();
        WorkJobEntity workJobEntity = workJobService.getById(workId);
        if (workJobEntity!=null){
            listData.add(workJobEntity.getProvincesId().toString());
            listData.add(workJobEntity.getCitysId().toString());
            listData.add(workJobEntity.getAreasId().toString());
        }
        return R.ok().put("data",listData);
    }


    /**
     * 根据职位的Id显示出来行业类型
     */
    @GetMapping("/industory-option/{workId}")
    public R jobIndustoryOptionArr(@PathVariable("workId")String workId){
        ArrayList<String> listData = new ArrayList<>();
        WorkJobEntity workJobEntity = workJobService.getById(workId);
        if (workJobEntity!=null){
            listData.add(workJobEntity.getTradeId().toString());
            listData.add(workJobEntity.getClassifyId().toString());
            //listData.add(workJobEntity.getJobTypeId().toString());
        }
        return R.ok().put("data",listData);
    }


    /**
     * 根据职位Id加载出来证书
     */
    @GetMapping("/certificates-option/{workId}")
    public R jobCertificatesOptionArr(@PathVariable("workId")String workId){
        QueryWrapper<PositionCertificateEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("position_id",workId);
        List<PositionCertificateEntity> positionCertificateEntityList = positionCertificateDao.selectList(wrapper);
        ArrayList<String> listData = (ArrayList<String>) positionCertificateEntityList.stream().map(item -> item.getCertificateId().toString()).collect(Collectors.toList());
        return R.ok().put("data",listData);
    }

    /**
     * 根据职位信息加载出来福利信息
     */
    @GetMapping("/walfare-option/{workId}")
    public R jobWalfareOptionArr(@PathVariable("workId")String workId){
        QueryWrapper<PositionWelfareEntity> wrapper = new QueryWrapper();
        wrapper.eq("position_id",workId);
        List<PositionWelfareEntity> positionWelfareEntities = positionWelfareDao.selectList(wrapper);
        List<String> listData = positionWelfareEntities.stream().map(item -> item.getWelfareId().toString()).collect(Collectors.toList());
        return R.ok().put("data",listData);
    }

    /**
     * 职位审核
     */
    @PostMapping("/approve/{workJobId}/{ispass}")
    @RequiresPermissions("workjobs:workjob:approve")
    public R  workJobApprove(@PathVariable("workJobId")String workJobId,
                             @PathVariable("ispass")String ispass){

        WorkJobEntity workJobEntity = workJobService.getById(workJobId);

        if ("1".equals(ispass)){
           if (CommonBusinessStatus.POSITION_PUBLISH_NOT_HAVE.equals(workJobEntity.getJobIssueStatus())
                        ||
                        CommonBusinessStatus.POSITION_PUBLISH_HAVEING.equals(workJobEntity.getJobIssueStatus())
                     ){
                return R.error("请先发布职位信息");
            }else if (workJobEntity.getJobApproveStatus().equals(CommonBusinessStatus.POSITION_NOT_HAVE_APPROVE)){
               return R.error("请先查看职位信息");
           }


            workJobEntity.setJobApproveStatus(10110);
            workJobEntity.setJobIsPass(Integer.parseInt(ispass));
            int isUpdate = workJobDao.updateById(workJobEntity);
            if (isUpdate>0){
                return R.ok();
            }else{
                return R.error("更新失败");
            }
        }
        if ("0".equals(ispass)){
            if (CommonBusinessStatus.POSITION_PUBLISH_NOT_HAVE.equals(workJobEntity.getJobIssueStatus())
                    ||
                    CommonBusinessStatus.POSITION_PUBLISH_HAVEING.equals(workJobEntity.getJobIssueStatus())
            ){
                return R.error("请先发布职位信息");
            }else   if (workJobEntity.getJobApproveStatus().equals(CommonBusinessStatus.POSITION_NOT_HAVE_APPROVE)){
                return R.error("请先查看职位信息");
            }

            workJobEntity.setJobApproveStatus(10110);
            workJobEntity.setJobIsPass(Integer.parseInt(ispass));
            int isUpdate = workJobDao.updateById(workJobEntity);
            if (isUpdate>0){
                return R.ok();
            }else{
                return R.error("更新失败");
            }
        }
        return R.ok();
    }



    /**
     * 职位发布
     */
    @PostMapping("/publish/{workJobId}")
    @RequiresPermissions("workjobs:workjob:publish")
    public R publish(@PathVariable("workJobId") String workJobId){
        WorkJobEntity workJobEntity = workJobService.getById(workJobId);

        boolean isUpdata = workJobService.updateWorkPublishStatus(workJobEntity);
        if (isUpdata){
            return R.ok();
        }
        return R.error("更新失败，请联系管理员");
    }

    /**
     * 撤销发布
     */
    @PostMapping("/cancel-publish/{workJobId}")
    @RequiresPermissions("workjobs:workjob:cancelpublish")
    public R cancelPublish(@PathVariable("workJobId") String workJobId){
        QueryWrapper<WorkJobEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",workJobId);
        WorkJobEntity workJobEntity = workJobDao.selectOne(wrapper);
        workJobEntity.setJobIssueStatus(CommonBusinessStatus.POSITION_PUBLISH_NOT_HAVE);
        int isWork = workJobDao.updateById(workJobEntity);
        if (isWork>0){
            return R.ok();
        }else{
            return R.error();
        }
    }


    /**
     * 职位展示  OLD
     */
    @PostMapping("/showjob/{current}/{size}")
    public R showList(@PathVariable("current")String current,
                      @PathVariable("size")String size){
        R r = workJobService.showList(current,size);
        return r;
    }

    /**
     * 职位展示 最新的方法
     */
    @PostMapping("/showListWorkInfo/{current}/{size}")
    public R showListWorkInfo(@PathVariable("current")String current,
                              @PathVariable("size")String size,
                              @RequestBody QueryCondition queryCondition){
        if (current == null){
            current = "1";
        }
        if (size == null){
            size = "5";
        }

        R r = workJobService.showListWorkInfo(current,size,queryCondition);
        return r;
    }



    /**
     * 投递
     */
    @Transactional
    @RequestMapping("/deliver/{workJobId}/{userId}")
    @RequiresPermissions("workjobs:workjob:deliver")
    public R deliver(@PathVariable("workJobId") String workJobId,
                     @PathVariable("userId")String userId){

        QueryWrapper<ResumeEntity> resumeEntityQueryWrapper = new QueryWrapper<>();
        resumeEntityQueryWrapper.eq("user_id",userId);
        ResumeEntity resumeEntity = resumeDao.selectOne(resumeEntityQueryWrapper);
        if (resumeEntity == null){
            throw new RRException("请先上传简历");
        }

        if (!(resumeEntity.getResumeApproveStatus().equals(CommonBusinessStatus.RESUME_HAVING_APPROVE) && resumeEntity.getIsPass().equals(1))){
            throw new RRException("简历审核未通过");
        }
        boolean isDeliver = workJobService.deliver(workJobId,userId);
        QueryWrapper<WorkJobEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",workJobId);
        WorkJobEntity workJobEntity = workJobService.getOne(wrapper);
        DeliveryCreateUserPositionEntity deliveryCreateUserPositionEntity = new DeliveryCreateUserPositionEntity();
        deliveryCreateUserPositionEntity.setUserDeliveryId(Long.parseLong(userId));
        deliveryCreateUserPositionEntity.setPositionId(workJobId);
        deliveryCreateUserPositionEntity.setUserCreatePositionId(workJobEntity.getCreateUserId());
        deliveryCreateUserPositionEntity.setFeedback(0);
        deliveryCreateUserPositionDao.insert(deliveryCreateUserPositionEntity);
        return R.ok().put("data",isDeliver);
    }

    /**
     *
     * 这个方法是个求职者用户用的
     * 根据用户的Id查询出来投递的职位
     */
    @GetMapping("/workPosition/{userId}/{current}/{size}")
    public R getDeliverUserId(@PathVariable("userId")String userId,
                              @PathVariable("current")String current,
                              @PathVariable("size")String size){

        R r = workJobService.IPageList(userId,current,size);
        return r;
    }

    /**
     *  这个方法是给企业用的    根据用户的Id,查询出来有那些人投递了我的职位
     */
    @GetMapping("/userDeliverSomePosition/{userId}/{current}/{size}")
    public R queryDeliverPosition(@PathVariable("userId")String userId,
                                  @PathVariable("current")String current,
                                  @PathVariable("size")String size){
        R r = workJobService.queryDeliverPosition(userId,current,size);
        return  r;
    }

    //企业用户审判这个求职者用户是否和这个职位相互匹配
    @PostMapping("/fit/{deliveryId}/{positionId}/{feedback}")
    public R fit(@PathVariable("deliveryId")String deliveryId,
                         @PathVariable("positionId")String positionId,
                         @PathVariable("feedback") Integer feedback){

        R r = workJobService.fitOrNotFit(deliveryId,positionId,feedback);
        return r;
    }

    @PostMapping("/notFit/{deliveryId}/{positionId}/{feedback}")
    public R notFit(@PathVariable("deliveryId")String deliveryId,
                    @PathVariable("positionId")String positionId,
                    @PathVariable("feedback") Integer feedback) {

        R r = workJobService.fitOrNotFit(deliveryId, positionId, feedback);
        return r;
    }
}
